package com.piper.long_connection.server;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.Objects;

/**
 * 服务端消息处理
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("服务端收到消息：" + msg);
        if (Objects.equals("ping", msg)) {
            ctx.channel().writeAndFlush("pong");
        } else if (Objects.equals("exit", msg)) {
            ChannelFuture future = ctx.writeAndFlush("see you");
            future.addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.channel().writeAndFlush("你好");
        }
    }

    @Override
    public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {

                //清除超时会话
                ChannelFuture writeAndFlush = ctx.writeAndFlush("you will close");
//                ctx.channel().close();
                writeAndFlush.addListener(ChannelFutureListener.CLOSE);
//                writeAndFlush.addListener(new ChannelFutureListener() {
//                    @Override
//                    public void operationComplete(ChannelFuture future) throws Exception {
//                        future.channel().close();
//                    }
//                });
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 新客户端接入
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    /**
     * 客户端断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    /**
     * 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

}
